package constant.milk.periodapp.setting;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.IntentSender.SendIntentException;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.drive.Drive;
import com.google.android.gms.drive.DriveApi;
import com.google.android.gms.drive.DriveApi.DriveContentsResult;
import com.google.android.gms.drive.DriveApi.MetadataBufferResult;
import com.google.android.gms.drive.DriveContents;
import com.google.android.gms.drive.DriveFile;
import com.google.android.gms.drive.DriveFolder;
import com.google.android.gms.drive.DriveFolder.DriveFileResult;
import com.google.android.gms.drive.Metadata;
import com.google.android.gms.drive.MetadataBuffer;
import com.google.android.gms.drive.MetadataChangeSet;
import com.google.android.gms.drive.query.Filters;
import com.google.android.gms.drive.query.Query;
import com.google.android.gms.drive.query.SearchableField;
import com.google.android.gms.drive.widget.DataBufferAdapter;

import constant.milk.periodapp.R;
import constant.milk.periodapp.SuperActivity;
import constant.milk.periodapp.database.DbAdapter;
import constant.milk.periodapp.dialog.MilkListDialog;
import constant.milk.periodapp.dialog.MilkProgressDialog;
import constant.milk.periodapp.dialog.MilkListDialog.ListCallBack;
import constant.milk.periodapp.dialog.MilkYesNoDialog;
import constant.milk.periodapp.util.MilkShared;
import constant.milk.periodapp.util.MilkUtil;

public class DataActivity extends SuperActivity
{
	protected static final int REQUEST_CODE_RESOLUTION = 1;
	
	private static final String DRIVE_DATA1 = "period1/db";
	private static final String DRIVE_DATA2 = "period2/db";
	private static final String DRIVE_DATA3 = "period3/db";
	
	private static final String DRIVE_FILE_NAME_1 = "_드라이브_1번_백업파일";
	private static final String DRIVE_FILE_NAME_2 = "_드라이브_2번_백업파일";
	private static final String DRIVE_FILE_NAME_3 = "_드라이브_3번_백업파일";
	
	private String DIRNAME = "";
	private String FILENAME = "";
	
	private String DRIVE_FILENAME = "";
	
	private TextView backTextView;
	private TextView backUpTextView;
	private TextView backUpTitleTextView;
	
	private ListView listView;
	
	private TextView driveGoogleIdTextView;
	private TextView driveGoogleIdTitleTextView;
	
	private TextView drive1IconTextView;
	private TextView drive1DateTextView;
	private TextView drive1RollBackTextView;
	private TextView drive1LineTextView;
	private TextView drive1BackUpTextView;
	
	private TextView drive2IconTextView;
	private TextView drive2DateTextView;
	private TextView drive2RollBackTextView;
	private TextView drive2LineTextView;
	private TextView drive2BackUpTextView;
	
	private TextView drive3IconTextView;
	private TextView drive3DateTextView;
	private TextView drive3RollBackTextView;
	private TextView drive3LineTextView;
	private TextView drive3BackUpTextView;
	
	private File [] readFiles;
	
	private File selectFile;
	
	private PopupWindow pw;
	private View rollBackTextView;
	private View emailTextView;
	private View deleteTextView;
	
	private MilkYesNoDialog yesNoDialog;
	
	private GoogleApiClient googleApiClient;
	
	private Metadata metaData1;
	private Metadata metaData2;
	private Metadata metaData3;
	
	private MilkProgressDialog progressDialog;
	
	private Handler rollBackHandler = new Handler()
	{
		@Override
		public void handleMessage(Message msg)
		{
			super.handleMessage(msg);
			
			progressDialog.dismiss();
			
			boolean flag = (boolean) msg.obj;
			
			if (flag)
			{
				MilkUtil.showToast(superContext, "복구에 성공 하였습니다.");
				setResult(Activity.RESULT_OK);
				finish();
			}
			else
			{
				MilkUtil.showToast(superContext, "복구 실패! 개발자에게 문의해 주세요.");
			}
		}
	};
	
	private Handler backUpHandler = new Handler()
	{
		@Override
		public void handleMessage(Message msg)
		{
			super.handleMessage(msg);
			
			progressDialog.dismiss();
			
			MilkUtil.showToast(superContext, "백업 실패! 개발자에게 문의해 주세요.");
		}
	};
	
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.data_activity);
		
		setFindViewId();
		setOnClick();
		setData();
	}
	
	private void onGoogleApiClient()
	{
		progressDialog = new MilkProgressDialog(superContext); 
		progressDialog.show();
		
		new Thread()
		{
			@Override
			public void run()
			{
				if (googleApiClient == null) 
				{
					googleApiClient = new GoogleApiClient.Builder(superContext)
					.addApi(Drive.API)
		            .addScope(Drive.SCOPE_FILE)
		            .addScope(Drive.SCOPE_APPFOLDER)
		            .setAccountName(driveGoogleIdTitleTextView.getText().toString())
		            .addConnectionCallbacks(new ConnectionCallbacks()
					{
						@Override
						public void onConnectionSuspended(int cause)
						{
						}
						
						@Override
						public void onConnected(Bundle connectionHint)
						{
							progressDialog.dismiss();
							
							setDriveData();
						}
					})
		            .addOnConnectionFailedListener(new OnConnectionFailedListener()
					{
						@Override
						public void onConnectionFailed(ConnectionResult result)
						{
							progressDialog.dismiss();
							
					        if (!result.hasResolution()) 
					        {
					            GooglePlayServicesUtil.getErrorDialog(result.getErrorCode(), (Activity) superContext, 0).show();
					            return;
					        }
					        try {
					            result.startResolutionForResult((Activity) superContext, REQUEST_CODE_RESOLUTION);
					        } catch (SendIntentException e) 
					        {
					        }
						}
					})
					.build();
					
		        }
				
		        googleApiClient.connect();
			}
			
		}.start();
	}
	
	private boolean setDriveData()
	{
		metaData1 = null;
		metaData2 = null;
		metaData3 = null;
		
		try
		{
			Query query1 = new Query.Builder()
			.addFilter(Filters.and(Filters.eq(SearchableField.MIME_TYPE, DRIVE_DATA1),
					Filters.eq(SearchableField.TITLE, getString(R.string.appname) + DRIVE_FILE_NAME_1)))
			.build();
			Drive.DriveApi.query(googleApiClient, query1)
			.setResultCallback(new ResultCallback<DriveApi.MetadataBufferResult>()
			{
				@Override
				public void onResult(MetadataBufferResult result)
				{
					drive1BackUpTextView.setVisibility(View.VISIBLE);
					
					if (!result.getStatus().isSuccess()) 
			        {
						drive1IconTextView.setBackgroundResource(R.drawable.ic_drive_def);
						
						drive1DateTextView.setText("");
						drive1RollBackTextView.setVisibility(View.GONE);
						drive1LineTextView.setVisibility(View.GONE);
			            return;
			        }
			        
			        MetadataBuffer mb = result.getMetadataBuffer();
			        
			        if (mb.getCount() > 0)
					{
			        	metaData1 = mb.get(0);
						
						drive1IconTextView.setBackgroundResource(R.drawable.ic_drive_push);
						
						drive1DateTextView.setText(metaData1.getDescription());
						drive1RollBackTextView.setVisibility(View.VISIBLE);
						drive1LineTextView.setVisibility(View.VISIBLE);
					}
			        else
			        {
			        	drive1IconTextView.setBackgroundResource(R.drawable.ic_drive_def);
			        	
			        	drive1DateTextView.setText("");
						drive1RollBackTextView.setVisibility(View.GONE);
						drive1LineTextView.setVisibility(View.GONE);
			        }
				}
			});
			
			Query query2 = new Query.Builder()
			.addFilter(Filters.and(Filters.eq(SearchableField.MIME_TYPE, DRIVE_DATA2),
					Filters.eq(SearchableField.TITLE, getString(R.string.appname) + DRIVE_FILE_NAME_2)))
			.build();
			Drive.DriveApi.query(googleApiClient, query2)
			.setResultCallback(new ResultCallback<DriveApi.MetadataBufferResult>()
			{
				@Override
				public void onResult(MetadataBufferResult result)
				{
					drive2BackUpTextView.setVisibility(View.VISIBLE);
					
					if (!result.getStatus().isSuccess()) 
			        {
						drive2IconTextView.setBackgroundResource(R.drawable.ic_drive_def);
						
						drive2DateTextView.setText("");
						drive2RollBackTextView.setVisibility(View.GONE);
						drive2LineTextView.setVisibility(View.GONE);
			            return;
			        }
			        
			        MetadataBuffer mb = result.getMetadataBuffer();
			        
			        if (mb.getCount() > 0)
					{
			        	metaData2 = mb.get(0);
						
						drive2IconTextView.setBackgroundResource(R.drawable.ic_drive_push);
						
						drive2DateTextView.setText(metaData2.getDescription());
						drive2RollBackTextView.setVisibility(View.VISIBLE);
						drive2LineTextView.setVisibility(View.VISIBLE);
					}
			        else
			        {
			        	drive2IconTextView.setBackgroundResource(R.drawable.ic_drive_def);
			        	
			        	drive2DateTextView.setText("");
						drive2RollBackTextView.setVisibility(View.GONE);
						drive2LineTextView.setVisibility(View.GONE);
			        }
				}
			});
			
			Query query3 = new Query.Builder()
			.addFilter(Filters.and(Filters.eq(SearchableField.MIME_TYPE, DRIVE_DATA3),
					Filters.eq(SearchableField.TITLE, getString(R.string.appname) + DRIVE_FILE_NAME_3)))
			.build();
			Drive.DriveApi.query(googleApiClient, query3)
			.setResultCallback(new ResultCallback<DriveApi.MetadataBufferResult>()
			{
				@Override
				public void onResult(MetadataBufferResult result)
				{
					drive3BackUpTextView.setVisibility(View.VISIBLE);
					
					if (!result.getStatus().isSuccess()) 
			        {
						drive3IconTextView.setBackgroundResource(R.drawable.ic_drive_def);
						
						drive3DateTextView.setText("");
						drive3RollBackTextView.setVisibility(View.GONE);
						drive3LineTextView.setVisibility(View.GONE);
			            return;
			        }
			        
			        MetadataBuffer mb = result.getMetadataBuffer();
			        
			        if (mb.getCount() > 0)
					{
			        	metaData3 = mb.get(0);
						
						drive3IconTextView.setBackgroundResource(R.drawable.ic_drive_push);
						
						drive3DateTextView.setText(metaData3.getDescription());
						drive3RollBackTextView.setVisibility(View.VISIBLE);
						drive3LineTextView.setVisibility(View.VISIBLE);
					}
			        else
			        {
			        	drive3IconTextView.setBackgroundResource(R.drawable.ic_drive_def);
			        	
			        	drive3DateTextView.setText("");
						drive3RollBackTextView.setVisibility(View.GONE);
						drive3LineTextView.setVisibility(View.GONE);
			        }
				}
			});
		} catch (Exception e)
		{
			e.printStackTrace();
			MilkUtil.showToast(superContext, "구글 드라이브에서 백업 파일을 가져오는데 실패 하였습니다. 개발자에게 문의해주세요.");
			return false;
		}
		
		return true;
	}
	
	@Override
	protected void onDestroy()
	{
		super.onDestroy();
		
		if (googleApiClient != null) 
		{
            googleApiClient.disconnect();
            googleApiClient = null;
        }
	}
	
	@Override
	protected void setFindViewId()
	{
		backTextView = (TextView) findViewById(R.id.dataBackTextView);
		backUpTextView = (TextView) findViewById(R.id.dataBackUpTextView);
		backUpTitleTextView = (TextView) findViewById(R.id.dataBackUpTitleTextView);
		
		listView = (ListView) findViewById(R.id.dataListView);
		
		driveGoogleIdTextView = (TextView) findViewById(R.id.dataDriveGoogleIdTextView);
		driveGoogleIdTitleTextView = (TextView) findViewById(R.id.dataDriveGoogleIdTitleTextView);
		
		drive1IconTextView = (TextView) findViewById(R.id.dataDrive1IconTextView);
		drive1DateTextView = (TextView) findViewById(R.id.dataDrive1DateTextView);
		drive1RollBackTextView = (TextView) findViewById(R.id.dataDrive1RollBackTextView);
		drive1LineTextView = (TextView) findViewById(R.id.dataDrive1LineTextView);
		drive1BackUpTextView = (TextView) findViewById(R.id.dataDrive1BackUpTextView);
		
		drive2IconTextView = (TextView) findViewById(R.id.dataDrive2IconTextView);
		drive2DateTextView = (TextView) findViewById(R.id.dataDrive2DateTextView);
		drive2RollBackTextView = (TextView) findViewById(R.id.dataDrive2RollBackTextView);
		drive2LineTextView = (TextView) findViewById(R.id.dataDrive2LineTextView);
		drive2BackUpTextView = (TextView) findViewById(R.id.dataDrive2BackUpTextView);
		
		drive3IconTextView = (TextView) findViewById(R.id.dataDrive3IconTextView);
		drive3DateTextView = (TextView) findViewById(R.id.dataDrive3DateTextView);
		drive3RollBackTextView = (TextView) findViewById(R.id.dataDrive3RollBackTextView);
		drive3LineTextView = (TextView) findViewById(R.id.dataDrive3LineTextView);
		drive3BackUpTextView = (TextView) findViewById(R.id.dataDrive3BackUpTextView);
	}

	@Override
	protected void setOnClick()
	{
		backTextView.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				finish();
			}
		});
		
		backUpTextView.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				yesNoDialog = new MilkYesNoDialog(superContext, "알림", "SD카드로 백업 하시겠습니까?", 
						new OnClickListener()
				{
					@Override
					public void onClick(View v)
					{
						yesNoDialog.dismiss();
						
						Calendar cal = Calendar.getInstance();
						int year = cal.get(Calendar.YEAR);
						int month = cal.get(Calendar.MONTH);
						int day = cal.get(Calendar.DAY_OF_MONTH);
						String time = cal.get(Calendar.HOUR_OF_DAY) + "" + cal.get(Calendar.MINUTE) + "" + cal.get(Calendar.SECOND);
						
						String date = MilkUtil.getDateDB(year, month+1, day);
						
						date = date.replace(" ", "");
						
						FILENAME = DIRNAME + "_" + date + "_" + time;
						
						if (setSaveData())
						{
							MilkUtil.showToast(superContext, "SD카드로 백업에 성공 하였습니다.");
							setSdCardData();
						}
						else
						{
							MilkUtil.showToast(superContext, "백업 실패! 개발자에게 문의해 주세요.");
						}
					}
				});
				
				yesNoDialog.show();
			}
		});
		
		backUpTitleTextView.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				yesNoDialog = new MilkYesNoDialog(superContext, "알림", "SD카드로 백업 하시겠습니까?", 
						new OnClickListener()
				{
					@Override
					public void onClick(View v)
					{
						yesNoDialog.dismiss();
						
						Calendar cal = Calendar.getInstance();
						int year = cal.get(Calendar.YEAR);
						int month = cal.get(Calendar.MONTH);
						int day = cal.get(Calendar.DAY_OF_MONTH);
						String time = cal.get(Calendar.HOUR_OF_DAY) + "" + cal.get(Calendar.MINUTE) + "" + cal.get(Calendar.SECOND);
						
						String date = MilkUtil.getDateDB(year, month+1, day);
						
						date = date.replace(" ", "");
						
						FILENAME = DIRNAME + "_" + date + "_" + time;
						
						if (setSaveData())
						{
							MilkUtil.showToast(superContext, "SD카드로 백업에 성공 하였습니다.");
							setSdCardData();
						}
						else
						{
							MilkUtil.showToast(superContext, "백업 실패! 개발자에게 문의해 주세요.");
						}
					}
				});
				
				yesNoDialog.show();
			}
		});
		
		driveGoogleIdTextView.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				ArrayList<String> emailList = new ArrayList<String>();
				
				AccountManager am = (AccountManager) getSystemService(Context.ACCOUNT_SERVICE);
		        Account[] accounts = am.getAccounts();
		        
		        if (accounts.length > 0)
				{
		        	for (int i = 0; i < accounts.length; i++)
					{
						emailList.add(accounts[i].name);
					}
				}
		        else
		        {
		        	MilkUtil.showToast(superContext, "계정이 하나도 없습니다.");
		        	return;
		        }
				
				MilkListDialog dialog = new MilkListDialog(superContext, "계정을 선택해 주세요.", new ListCallBack()
				{
					@Override
					public void getData(String data)
					{
						MilkShared s = new MilkShared(superContext);
						s.setGoogleId(data);
						
						driveGoogleIdTitleTextView.setText(data);
						
						if (googleApiClient != null) 
						{
				            googleApiClient.disconnect();
				            googleApiClient = null;
				        }
						
						onGoogleApiClient();
					}
				}, emailList);
				
				dialog.show();
			}
		});
		
		driveGoogleIdTitleTextView.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				ArrayList<String> emailList = new ArrayList<String>();
				
				AccountManager am = (AccountManager) getSystemService(Context.ACCOUNT_SERVICE);
				Account[] accounts = am.getAccounts();
				
				if (accounts.length > 0)
				{
					for (int i = 0; i < accounts.length; i++)
					{
						emailList.add(accounts[i].name);
					}
				}
				else
				{
					MilkUtil.showToast(superContext, "계정이 하나도 없습니다.");
					return;
				}
				
				MilkListDialog dialog = new MilkListDialog(superContext, "계정을 선택해 주세요.", new ListCallBack()
				{
					@Override
					public void getData(String data)
					{
						MilkShared s = new MilkShared(superContext);
						s.setGoogleId(data);
						
						driveGoogleIdTitleTextView.setText(data);
						
						if (googleApiClient != null) 
						{
							googleApiClient.disconnect();
							googleApiClient = null;
						}
						
						onGoogleApiClient();
					}
				}, emailList);
				
				dialog.show();
			}
		});
		
		drive1RollBackTextView.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				yesNoDialog = new MilkYesNoDialog(superContext, "알림", "복구 하시겠습니까?", 
						new OnClickListener()
				{
					@Override
					public void onClick(View v)
					{
						yesNoDialog.dismiss();
						
						setDriveRollBackData(metaData1);
					}
				});
				
				yesNoDialog.show();
			}
		});
		
		drive1BackUpTextView.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				yesNoDialog = new MilkYesNoDialog(superContext, "알림", "백업 하시겠습니까?", 
						new OnClickListener()
				{
					@Override
					public void onClick(View v)
					{
						yesNoDialog.dismiss();
						
						setDriveCheckData(DRIVE_DATA1);
					}
				});
				
				yesNoDialog.show();
			}
		});

		drive2RollBackTextView.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				yesNoDialog = new MilkYesNoDialog(superContext, "알림", "복구 하시겠습니까?", 
						new OnClickListener()
				{
					@Override
					public void onClick(View v)
					{
						yesNoDialog.dismiss();
						
						setDriveRollBackData(metaData2);
					}
				});
				
				yesNoDialog.show();
			}
		});
		
		drive2BackUpTextView.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				yesNoDialog = new MilkYesNoDialog(superContext, "알림", "백업 하시겠습니까?", 
						new OnClickListener()
				{
					@Override
					public void onClick(View v)
					{
						yesNoDialog.dismiss();
						
						setDriveCheckData(DRIVE_DATA2);
					}
				});
				
				yesNoDialog.show();
			}
		});
		
		drive3RollBackTextView.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				yesNoDialog = new MilkYesNoDialog(superContext, "알림", "복구 하시겠습니까?", 
						new OnClickListener()
				{
					@Override
					public void onClick(View v)
					{
						yesNoDialog.dismiss();
						
						setDriveRollBackData(metaData3);
					}
				});
				
				yesNoDialog.show();
			}
		});
		
		drive3BackUpTextView.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				yesNoDialog = new MilkYesNoDialog(superContext, "알림", "백업 하시겠습니까?", 
						new OnClickListener()
				{
					@Override
					public void onClick(View v)
					{
						yesNoDialog.dismiss();
						
						setDriveCheckData(DRIVE_DATA3);
					}
				});
				
				yesNoDialog.show();
			}
		});
	}

	@Override
	protected void setData()
	{
		setSdCardData();
		
		MilkShared s = new MilkShared(superContext);
		
		String googleId = s.getGoogleId();
		
		if (googleId.equals(""))
		{
			driveGoogleIdTitleTextView.setText("눌러서 구글 계정을 추가해 주세요.");
			
			drive1DateTextView.setText("");
			drive1RollBackTextView.setVisibility(View.INVISIBLE);
			drive1LineTextView.setVisibility(View.INVISIBLE);
			drive1BackUpTextView.setVisibility(View.INVISIBLE);
			
			drive2DateTextView.setText("");
			drive2RollBackTextView.setVisibility(View.INVISIBLE);
			drive2LineTextView.setVisibility(View.INVISIBLE);
			drive2BackUpTextView.setVisibility(View.INVISIBLE);
			
			drive3DateTextView.setText("");
			drive3RollBackTextView.setVisibility(View.INVISIBLE);
			drive3LineTextView.setVisibility(View.INVISIBLE);
			drive3BackUpTextView.setVisibility(View.INVISIBLE);
		}
		else
		{
			driveGoogleIdTitleTextView.setText(googleId);
			
			onGoogleApiClient();
		}
	}

	private void setSdCardData()
	{
		DIRNAME = getString(R.string.appname);
		
		ArrayList<File> list = new ArrayList<File>();
		
		try
		{
			File directory = new File(Environment.getExternalStorageDirectory() + "/" 
										+ DIRNAME);
			
			readFiles = directory.listFiles(new FilenameFilter()
			{
				@Override
				public boolean accept(File dir, String filename)
				{
					return filename.endsWith(".db");
				}
			});
		} catch (Exception e)
		{
			e.printStackTrace();
		}
		
		if (readFiles != null)
		{
			for (int i = readFiles.length - 1; i > -1 ; i--)
			{
				list.add(readFiles[i]);
			}
		}
		
		setPopWindow();
		
		listView.setOnItemClickListener(oicl);
		
		DataAdapter listAdapter = new DataAdapter(
				superContext, R.layout.list_item_data, list);
		listView.setAdapter(listAdapter);
	}
	
	private void setPopWindow()
	{
		LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		View v = inflater.inflate(R.layout.popup_window_data, null);
		
		pw = new PopupWindow(v);
		pw.setWindowLayoutMode(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
		pw.setOutsideTouchable(true);
		pw.setBackgroundDrawable(getResources().getDrawable(R.drawable.bg_white));
		
		rollBackTextView = v.findViewById(R.id.popupDataRollBackView);
		emailTextView = v.findViewById(R.id.popupDataEmailView);
		deleteTextView = v.findViewById(R.id.popupDataDeleteView);
		
		rollBackTextView.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				pw.dismiss();
				
				yesNoDialog = new MilkYesNoDialog(superContext, "알림", "복구 하시겠습니까?", 
						new OnClickListener()
				{
					@Override
					public void onClick(View v)
					{
						yesNoDialog.dismiss();
						
						if (setRollBankData(selectFile))
						{
							MilkUtil.showToast(superContext, "복구에 성공 하였습니다.");
							setResult(Activity.RESULT_OK);
							finish();
						}
						else
						{
							MilkUtil.showToast(superContext, "복구 실패! 개발자에게 문의해 주세요.");
						}
					}
				});
				
				yesNoDialog.show();
			}
		});
		
		emailTextView.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				pw.dismiss();
				
				ArrayList<String> emailList = new ArrayList<String>();
				
				AccountManager am = (AccountManager) getSystemService(Context.ACCOUNT_SERVICE);
		        Account[] accounts = am.getAccounts();
		        
		        if (accounts.length > 0)
				{
		        	for (int i = 0; i < accounts.length; i++)
					{
						emailList.add(accounts[i].name);
					}
				}
		        else
		        {
		        	MilkUtil.showToast(superContext, "메일 계정이 하나도 없습니다.");
		        	return;
		        }
				
				MilkListDialog dialog = new MilkListDialog(superContext, "메일을 선택해 주세요.", new ListCallBack()
				{
					@Override
					public void getData(String data)
					{
						Uri uri = Uri.fromFile(selectFile);
						
						String [] email = new String[]{data};
						
						Intent intent = new Intent(Intent.ACTION_SEND);
				        intent.putExtra(Intent.EXTRA_EMAIL, email);
						intent.setType("plain/text");
						intent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.appname)); 
						intent.putExtra(Intent.EXTRA_TEXT, getString(R.string.appname) + " 백업파일");
						
						// 파일 첨부
						intent.putExtra(Intent.EXTRA_STREAM, uri);
						startActivity(intent);
					}
				}, emailList);
				
				dialog.show();
			}
		});
		
		deleteTextView.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				pw.dismiss();
				
				yesNoDialog = new MilkYesNoDialog(superContext, "알림", "삭제 하시겠습니까?", 
						new OnClickListener()
				{
					@Override
					public void onClick(View v)
					{
						yesNoDialog.dismiss();
						
						if (setDelete(selectFile))
						{
							MilkUtil.showToast(superContext, "삭제에 성공 하였습니다.");
							setSdCardData();
						}
						else
						{
							MilkUtil.showToast(superContext, "삭제 실패! 개발자에게 문의해 주세요.");
						}
					}
				});
				
				yesNoDialog.show();
			}
		});
	}
	
	private OnItemClickListener oicl = new OnItemClickListener()
	{
		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id)
		{
			selectFile = (File) parent.getItemAtPosition(position);
			
			pw.showAsDropDown(view);
		}
	};
	
	private boolean setSaveData()
	{
		DbAdapter adapter = DbAdapter.getInstance();
		String path = adapter.getDbPath(superContext);
		adapter.close();
		
		FileInputStream fis = null;
		FileOutputStream fos = null;
		try
		{
			File readfile = new File(path);
			
			if (!Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()))
			{
				return false;
			}
			
			fis = new FileInputStream(readfile);
			
			File directory = new File(Environment.getExternalStorageDirectory() + "/" + DIRNAME);
			
			if (!directory.exists())
			{
				directory.mkdir();
			}
			
			String directoryPath = directory.getPath();
			
			File writefile = new File(directoryPath + "/" + FILENAME + ".db");
			
			fos = new FileOutputStream(writefile);
			
			byte [] buffer = new byte[1024];
			
			int bufBytes = 0;
			while ((bufBytes = fis.read(buffer)) != -1) 
			{
				fos.write(buffer, 0, bufBytes);
			}
			fos.flush();
			
		} catch (Exception e)
		{
			return false;
		} finally {
			try
			{
				if (fis != null) fis.close();
				if (fos != null) fos.close();
			} catch (IOException e)
			{
				e.printStackTrace();
				return false;
			}
		}
		
		return true;
	}
	
	private void setDriveRollBackData(Metadata metaData)
	{
		progressDialog = new MilkProgressDialog(superContext);
		progressDialog.show();
		
		DriveFile file = Drive.DriveApi.getFile(googleApiClient, metaData.getDriveId());
		
		file.open(googleApiClient, DriveFile.MODE_READ_ONLY, null).setResultCallback(
				new ResultCallback<DriveApi.DriveContentsResult>()
		{
			@Override
			public void onResult(DriveContentsResult result)
			{
				if (!result.getStatus().isSuccess()) 
	            {
	                return;
	            }
				
				final DriveContents driveContents = result.getDriveContents();
				
				new Thread()
				{
					@Override
					public void run()
					{
						Message msg = new Message();
						msg.obj = true;
						
						DbAdapter adapter = DbAdapter.getInstance();
						String dbPath = adapter.getDbPath(superContext);
						adapter.close();
						
						InputStream is = null;
						FileInputStream fis = null;
						FileOutputStream fosTemp = null;
						FileOutputStream fos = null;
						File tempFile = null;
						
						try
						{
							is = driveContents.getInputStream();
							
							tempFile = new File(Environment.getExternalStorageDirectory() + "/" 
									+ DIRNAME + "/임시파일.db");
							
							fosTemp = new FileOutputStream(tempFile);
							
							byte [] buffer = new byte[1024];
							
							int bufBytes = 0;
							while ((bufBytes = is.read(buffer)) != -1) 
							{
								fosTemp.write(buffer, 0, bufBytes);
							}
							fosTemp.flush();
							
							// 정상 디비 파일인지 체크
							SQLiteDatabase db = SQLiteDatabase.openDatabase(tempFile.getPath(), 
									null, SQLiteDatabase.OPEN_READONLY);
							
							if (db == null)
							{
								return;
							}
							else if (!db.isOpen())
							{
								db.close();
								return;
							}
							
							db.close();
							
							fis = new FileInputStream(tempFile.getPath());
							
							File writeFile = new File(dbPath);
							
							fos = new FileOutputStream(writeFile);
							
							bufBytes = 0;
							while ((bufBytes = fis.read(buffer)) != -1) 
							{
								fos.write(buffer, 0, bufBytes);
							}
							fos.flush();
							
						} catch (Exception e)
						{
							e.printStackTrace();
							msg.obj = false;
							rollBackHandler.sendMessage(msg);
							return;
						} finally {
							try
							{
								if (is != null) is.close();
								if (fis != null) fis.close();
								if (fos != null) fos.close();
								if (fosTemp != null) fosTemp.close();
								if (tempFile != null) tempFile.delete();
							} catch (IOException e)
							{
								e.printStackTrace();
								msg.obj = false;
								rollBackHandler.sendMessage(msg);
								return;
							}
						}
						
						msg.obj = true;
						rollBackHandler.sendMessage(msg);
					}
				}.start();
			}
		});
	}
	
	private void setDriveCheckData(final String mineType)
	{
		if (mineType.equals(DRIVE_DATA2))
		{
			if (metaData2 == null)
			{
				setDriveSaveData(mineType);
			}
			else
			{
				setDriveUpdateData(metaData2);
			}
		}
		else if (mineType.equals(DRIVE_DATA3))
		{
			if (metaData3 == null)
			{
				setDriveSaveData(mineType);
			}
			else
			{
				setDriveUpdateData(metaData3);
			}
		}
		else
		{
			if (metaData1 == null)
			{
				setDriveSaveData(mineType);
			}
			else
			{
				setDriveUpdateData(metaData1);
			}
		}
	}
	
	private void setDriveUpdateData(Metadata metaData)
	{
		progressDialog = new MilkProgressDialog(superContext);
		progressDialog.show();
		
		DriveFile file = Drive.DriveApi.getFile(googleApiClient, metaData.getDriveId());
		
		file.open(googleApiClient, DriveFile.MODE_WRITE_ONLY, null).setResultCallback(
				new ResultCallback<DriveApi.DriveContentsResult>()
		{
			
			@Override
			public void onResult(DriveContentsResult result)
			{
				if (!result.getStatus().isSuccess()) 
	            {
	                return;
	            }
				
				final DriveContents driveContents = result.getDriveContents();
				
				new Thread()
				{
					@Override
					public void run()
					{
						OutputStream os = driveContents.getOutputStream();
						FileInputStream fis = null;
						
						try
						{
							Calendar cal = Calendar.getInstance();
							int year = cal.get(Calendar.YEAR);
							int month = cal.get(Calendar.MONTH);
							int day = cal.get(Calendar.DAY_OF_MONTH);
							
							String date = MilkUtil.getDateCom(year, month+1, day);
							
							DbAdapter adapter = DbAdapter.getInstance();
							String path = adapter.getDbPath(superContext);
							adapter.close();
							
							File readfile = new File(path);
							fis = new FileInputStream(readfile);
							
							byte [] buffer = new byte[1024];
							
							int bufBytes = 0;
							while ((bufBytes = fis.read(buffer)) != -1) 
							{
								os.write(buffer, 0, bufBytes);
							}
							os.flush();
							
							MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
							.setDescription(date)
							.setStarred(true)
							.build();
							
							driveContents.commit(googleApiClient, changeSet).setResultCallback(
									new ResultCallback<Status>()
							{
								@Override
								public void onResult(Status result)
								{
									progressDialog.dismiss();
						        	
						            if (!result.getStatus().isSuccess()) 
						            {
						            	MilkUtil.showToast(superContext, "구글 드라이브 백업에 실패 하였습니다. 개발자에게 문의해주세요.");
						            	
						                return;
						            }
						            else
						            {
						            	MilkUtil.showToast(superContext, "구글 드라이브 백업에 성공 하였습니다");
						            	
						            	setDriveData();
						            	
						            	return;
						            }
								}
							});
							
						} catch (Exception e)
						{
							e.printStackTrace();
							driveContents.discard(googleApiClient);
							backUpHandler.sendMessage(new Message());
						} finally {
	            			try
	            			{
	            				if (fis != null) fis.close();
	            				if (os != null) os.close();
	            			} catch (IOException e)
	            			{
	            				e.printStackTrace();
	            				backUpHandler.sendMessage(new Message());
	            			}
	            		}
					}
					
				}.start();
			}
		});
	}
	
	private void setDriveSaveData(final String mineType)
	{
		progressDialog = new MilkProgressDialog(superContext);
		progressDialog.show();
		
		Drive.DriveApi.newDriveContents(googleApiClient).setResultCallback(
				new ResultCallback<DriveApi.DriveContentsResult>()
		{
			@Override
			public void onResult(DriveContentsResult result)
			{
				if (!result.getStatus().isSuccess()) 
	            {
	                return;
	            }
	            
	            final DriveContents driveContents = result.getDriveContents();

	            new Thread() 
	            {
	                @Override
	                public void run() 
	                {
	                    OutputStream os = driveContents.getOutputStream();
	                    FileInputStream fis = null;
	                    
	                    try {
	                    	
	                    	Calendar cal = Calendar.getInstance();
	                		int year = cal.get(Calendar.YEAR);
	                		int month = cal.get(Calendar.MONTH);
	                		int day = cal.get(Calendar.DAY_OF_MONTH);
	                		
	                		String date = MilkUtil.getDateCom(year, month+1, day);
	                		
	                		if (mineType.equals(DRIVE_DATA2))
	                		{
	                			DRIVE_FILENAME = getString(R.string.appname) + DRIVE_FILE_NAME_2;
	                		}
	                		else if (mineType.equals(DRIVE_DATA3))
	                		{
	                			DRIVE_FILENAME = getString(R.string.appname) + DRIVE_FILE_NAME_3;
	                		}
	                		else 
	                		{
	                			DRIVE_FILENAME = getString(R.string.appname) + DRIVE_FILE_NAME_1;
	                		}
	                		
	                		
	                		DbAdapter adapter = DbAdapter.getInstance();
	                		String path = adapter.getDbPath(superContext);
	                		adapter.close();
	                		
	                		File readfile = new File(path);
	                		fis = new FileInputStream(readfile);
	                		
	                		byte [] buffer = new byte[1024];
	            			
	            			int bufBytes = 0;
	            			while ((bufBytes = fis.read(buffer)) != -1) 
	            			{
	            				os.write(buffer, 0, bufBytes);
	            			}
	            			os.flush();
	            			
	            			MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
                            .setTitle(DRIVE_FILENAME)
                            .setMimeType(mineType)
                            .setDescription(date)
                            .setStarred(true).build();

		                    // create a file on root folder
		                    Drive.DriveApi.getRootFolder(googleApiClient)
		                            .createFile(googleApiClient, changeSet, driveContents)
		                            .setResultCallback(new ResultCallback<DriveFolder.DriveFileResult>()
									{
										@Override
										public void onResult(DriveFileResult result)
										{
											progressDialog.dismiss();
								        	
								            if (!result.getStatus().isSuccess()) 
								            {
								            	MilkUtil.showToast(superContext, "구글 드라이브 백업에 실패 하였습니다. 개발자에게 문의해주세요.");
								            	
								                return;
								            }
								            else
								            {
								            	MilkUtil.showToast(superContext, "구글 드라이브 백업에 성공 하였습니다");
								            	
								            	setDriveData();
								            	
								            	return;
								            }
										}
									});
	                		
	                    } catch (Exception e) 
	                    {
	                    	e.printStackTrace();
	                    	driveContents.discard(googleApiClient);
	                    	backUpHandler.sendMessage(new Message());
	                    } finally {
	            			try
	            			{
	            				if (fis != null) fis.close();
	            				if (os != null) os.close();
	            			} catch (IOException e)
	            			{
	            				e.printStackTrace();
	            				backUpHandler.sendMessage(new Message());
	            			}
	            		}
	                }
	            }.start();
			}
		});
	}
	
	private boolean setDelete(File selectFile)
	{
		if (selectFile == null)
		{
			return false;
		}
		
		String filePath = "";
		
		filePath = "/" + DIRNAME + "/";
		
		File file = new File(Environment.getExternalStorageDirectory() + filePath + selectFile.getName());
		
		return file.delete();
	}
	
	private boolean setRollBankData(File selectFile)
	{
		if (selectFile == null)
		{
			return false;
		}
		
		DbAdapter adapter = DbAdapter.getInstance();
		String path = adapter.getDbPath(superContext);
		adapter.close();
		
		FileInputStream fis = null;
		FileOutputStream fos = null;
		
		try
		{
			String filePath = selectFile.getPath();
			SQLiteDatabase db = SQLiteDatabase.openDatabase(filePath, 
					null, SQLiteDatabase.OPEN_READONLY);
			
			if (db == null)
			{
				return false;
			}
			else if (!db.isOpen())
			{
				db.close();
				return false;
			}
			
			db.close();
			
			fis = new FileInputStream(selectFile);
			
			File writeFile = new File(path);
			
			fos = new FileOutputStream(writeFile);
			
			byte [] buffer = new byte[1024];
			
			int bufBytes = 0;
			while ((bufBytes = fis.read(buffer)) != -1) 
			{
				fos.write(buffer, 0, bufBytes);
			}
			fos.flush();
			
		} catch (Exception e)
		{
			return false;
		} finally {
			try
			{
				if (fis != null) fis.close();
				if (fos != null) fos.close();
			} catch (IOException e)
			{
				e.printStackTrace();
				return false;
			}
		}
		
		return true;
	}
	
	@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) 
	{
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_RESOLUTION && resultCode == RESULT_OK) 
        {
            googleApiClient.connect();
        }
    }
	
	public class DataAdapter extends ArrayAdapter<File>
	{

		public DataAdapter(Context context, int resource, List<File> objects)
		{
			super(context, resource, objects);
		}
		
		@Override
		public View getView(int position, View convertView, ViewGroup parent)
		{
			View v = convertView;
			
			if (v == null) 
			{
				LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				v = inflater.inflate(R.layout.list_item_data, null);
			}
			
			File data = getItem(position);
			
			TextView tv = (TextView) v.findViewById(R.id.listItemFileTextView);
			
			tv.setText(data.getName());
			
			return v;
		}
	}
	
	public class DriveAdapter extends DataBufferAdapter<Metadata>
	{

		public DriveAdapter(Context context, int resource)
		{
			super(context, resource);
		}
		
		@Override
		public View getView(int position, View convertView, ViewGroup parent)
		{
			View v = convertView;
			
			if (v == null) 
			{
				LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				v = inflater.inflate(R.layout.list_item_data, null);
			}
			
			Metadata data = getItem(position);
			
			TextView tv = (TextView) v.findViewById(R.id.listItemFileTextView);
			
			tv.setText(data.getTitle());
			
			return v;
		}
	}
}
